<template>
  <div class="app-container">
    <div class="top-panel">
      <header-select @selectProject="getProject" />
      <el-button class="add-btn" type="primary" size="mini" icon="el-icon-plus" @click="handleAdd">新增</el-button>
    </div>
    <el-container>
      <el-main style="padding:0;">
        <el-table
          class="g-table-tree-expand-align"
          ref="table"
          v-loading="tableLoading"
          :data="tableData"
          row-key="fid"
          default-expand-all
          highlight-current-row
          size="small"
          height="calc(100vh - 150px)"
        >
          <el-table-column label="工程编码" prop="fnumber" show-overflow-tooltip min-width="150" class-name="expand-column" />
          <el-table-column label="工程名称" prop="fnameL2" show-overflow-tooltip min-width="150" />
          <el-table-column label="工程类型" align="center" min-width="100">
            <dict-tag slot-scope="{ row }" :options="dict.type.public_area_type" :value="row.publicareatype" />
          </el-table-column>
          <el-table-column label="占地面积(㎡)" min-width="90" prop="fbuildingterraarea" />

          <el-table-column label="其他信息" min-width="150">
            <template slot-scope="scope">
              <span v-if="scope.row.publicareatype === 4">桩基数量： {{ scope.row.pilenum ? scope.row.pilenum : 0 }} 根</span>
              <span v-else />
            </template>
          </el-table-column>
          <el-table-column label="创建人" align="center" min-width="60" prop="creatorName" />
          <el-table-column label="创建时间" prop="fcreatetime" align="center" width="150" />

          <el-table-column
            label="操作"
            width="250"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="scope.row.publicareatype == 5 ? $refs.EditFireCompart.open(scope.row) : handleUpdate(scope.row)"
              >修改
              </el-button>
              <el-button
                v-if="scope.row.publicareatype !=null && scope.row.publicareatype > 0"
                size="mini"
                type="text"
                icon="el-icon-picture-outline"
                @click="handlePlan(scope.row)"
              >平面图
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
              >删除
              </el-button>
              <el-button
                v-if="scope.row.publicareatype == 3"
                size="mini"
                type="text"
                icon="el-icon-plus"
                @click="openFireCompart(scope.row)"
              >防火分区
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-main>
    </el-container>
    <!-- 修改参数配置对话框 -->
    <el-dialog
      :title="editDialog.title"
      :close-on-click-modal="false"
      :visible.sync="editDialog.visible"
      :before-close="formDialogCloseHandel"
      width="900px"
      append-to-body
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        size="small"
        label-width="120px"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item
              label="工程类型"
              prop="publicareatype"
            >
              <div>
                <el-radio
                  v-for="o in projectTypeOptions"
                  :key="o.dictValue"
                  v-model="form.publicareatype"
                  :label="o.dictValue"
                  :disabled="form.fid != null && form.fid != ''"
                  border
                  @change="resetByRadio"
                >{{ o.dictLabel }}</el-radio>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider />
        <!-- 其他 -->
        <el-row v-if="form.publicareatype">
          <el-col :span="12">
            <el-form-item
              label="工程编码"
              prop="fnumber"
            >
              <el-input
                v-model="form.fnumber"
                placeholder="请输入"
                class="form-input"
                :maxlength="50"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="工程名称"
              prop="fnameL2"
            >
              <el-input
                v-model="form.fnameL2"
                placeholder="请输入"
                class="form-input"
                :maxlength="100"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="占地面积（㎡）"
              prop="fbuildingterraarea"
            >
              <el-input-number
                v-model="form.fbuildingterraarea"
                :controls="false"
                :min="0"
                :max="999999"
                class="form-input"
                :precision="2"
                placeholder="请输入"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
          <el-col
            v-if="form.publicareatype == 4"
            :span="12"
          >
            <el-form-item
              label="桩基数量"
              prop="pilenum"
            >
              <el-input-number v-model="form.pilenum" :precision="0" :min="0" :max="999999" style="width: 100%;" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          type="primary"
          :loading="loading"
          :disabled="loading"
          @click="submitForm"
        >确 定
        </el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 平面图管理窗口 -->
    <el-dialog
      title="平面图管理"
      :close-on-click-modal="false"
      :visible.sync="uploadData.dialogVisible"
      width="900px"
      append-to-body
      :before-close="clearPicture"
    >
      <el-row>
        <el-col :span="24">
          <el-upload
            ref="upload"
            class="plan-upload-btn"
            :before-upload="beforeUpload"
            name="file"
            :multiple="true"
            accept=".png, .jpg, .jpeg"
            list-type="picture-card"
            :action="uploadData.uploadAddress"
            :data="uploadData.extData"
            :headers="uploadData.headers"
            :file-list="uploadData.showFileList"
            :on-remove="handleRemovePic"
            :on-preview="handlePictureCardPreview"
          >
            <i class="el-icon-plus" />
          </el-upload>
        </el-col>
      </el-row>
    </el-dialog>
    <!-- 平面图预览 -->
    <el-dialog :visible.sync="uploadData.openPreview" top="5vh">
      <img width="100%" style="height: 80vh;" :src="uploadData.previewUrl" alt="">
    </el-dialog>

    <!-- 添加或修改防火分区 -->
    <EditFireCompart ref="EditFireCompart" v-model="showEditFireCompart" @ok="getBaseEngineeList" />
  </div>
</template>

<script>
// 基础管控-基础工程管理
import { flatList2tree } from '@/utils'
import {
  listBuildingManage,
  delBuildingManage,
  addBuildingManage,
  updateBuildingManage,
  delFile,
  listFile
} from '@/api/baseManage/buildingManage'
import HeaderSelect from '../statement/components/HeaderSelect'
import { getToken } from '@/utils/auth'
import EditFireCompart from './components/EditFireCompartment'

export default {
  name: 'BeManage',
  components: {
    HeaderSelect,
    EditFireCompart
  },
  dicts: ['public_area_type'],
  data() {
    return {
      /* 表格loading开关 */
      tableLoading: false,
      /* 表格数据 */
      tableData: [],
      /* 当前项目 */
      currentProject: {},
      /* 工程类型 */
      publicAreaTypeOptions: [],
      /* 编辑框标题 */
      editDialog: {
        title: '',
        visible: false
      },
      /* 初始化表单内容 */
      initForm: {},
      /* 表单 */
      form: {
        fid: null,
        fnumber: '',
        fnameL2: '',
        publicareatype: null,
        cfcurprojectid: '',
        fbuildingterraarea: 0,
        pilenum: 0
      },
      /* 表单规则 */
      rules: {
        fnumber: [
          { required: true, message: '工程编号不能为空', trigger: 'blur' }
        ],
        fnameL2: [
          { required: true, message: '工程名称不能为空', trigger: 'blur' }
        ]
      },
      /* 图片上传控件数据 */
      uploadData: {
        /* 上传文件附带额外参数 */
        extData: {},
        /* 展示图片列表 */
        showFileList: [],
        /* 新上传图片列表 */
        newFileList: [],
        /* 预览路径 */
        previewUrl: null,
        /* 预览窗口开关 */
        openPreview: false,
        /* 请求头 */
        headers: {
          Authorization: 'Bearer ' + getToken()
        },
        /* 文件上传地址 */
        uploadAddress: process.env.VUE_APP_BASE_API + '/gcxt/building/upload',
        /* 窗口开关标识 */
        dialogVisible: false
      },
      loading: false,
      showEditFireCompart: false
    }
  },
  computed: {
    /* 过滤主体楼栋和防火分区类型 */
    projectTypeOptions: function() {
      return this.publicAreaTypeOptions.filter(i => !['0', '5'].includes(i.dictValue))
    }
  },
  created() {
    this.$nextTick(() => {
      this.initForm = { ...this.form }
    })
    this.getDicts('public_area_type').then((response) => {
      this.publicAreaTypeOptions = response.data
    })
  },
  methods: {
    /* 项目选择组件回调函数 */
    getProject(project) {
      if (!project) {
        this.tableLoading = false
        return
      }
      this.currentProject = project
      this.getBaseEngineeList()
    },
    /* 获取基础工程列表 */
    getBaseEngineeList() {
      this.tableLoading = true
      const params = { typeIds: '1,2,3,4,5', cfcurprojectid: this.currentProject.id }
      listBuildingManage(params).then(
        (response) => {
          let data = response.data || []
          data.sort((a, b) => a.fnumber.localeCompare(b.fnumber))
          data = flatList2tree(data, { id: 'fid' })
          this.tableData = data
          this.tableLoading = false
        }
      ).catch(() => {
        this.tableLoading = false
      })
    },
    // 切换类型重置表单
    resetByRadio() {
      const radioValue = this.form.publicareatype
      if (radioValue != null) {
        const newFormData = { ...this.initForm }
        newFormData.publicareatype = radioValue
        newFormData.cfcurprojectid = this.currentProject.id
        this.$refs['form'].resetFields()
        this.form = { ...newFormData }
      }
    },
    /* 修改按钮操作 */
    handleUpdate(row) {
      this.editDialog.visible = true
      this.editDialog.title = '修改'
      this.form = { ...row }
      this.form.publicareatype = this.form.publicareatype + ''
    },
    /* 新增按钮操作 */
    handleAdd() {
      if (!this.currentProject.id) {
        this.$message.warning('请选择项目')
        return
      }
      this.form = { ...this.initForm }
      this.form.cfcurprojectid = this.currentProject.id
      this.editDialog.visible = true
      this.editDialog.title = '新增'
    },
    /** 提交按钮 */
    submitForm() {
      if (!this.form.publicareatype) {
        this.$message.warning('请选择工程类型')
        return
      }
      if (this.loading) {
        return
      }
      this.loading = true
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.fid) {
            updateBuildingManage(this.form).then((response) => {
              if (response.code === 200) {
                this.msgSuccess('修改成功')
                this.editDialog.visible = false
                this.getBaseEngineeList()
              }
            }).finally(() => {
              setTimeout(() => {
                this.loading = false
              }, 500)
            })
          } else {
            addBuildingManage(this.form).then((response) => {
              if (response.code === 200) {
                this.msgSuccess('新增成功')
                this.editDialog.visible = false
                this.getBaseEngineeList()
              }
            }).finally(() => {
              setTimeout(() => {
                this.loading = false
              }, 500)
            })
          }
        } else {
          setTimeout(() => {
            this.loading = false
          }, 500)
        }
      })
    },
    /* 取消按钮 */
    cancel() {
      this.$refs.form.clearValidate()
      this.editDialog.visible = false
    },
    formDialogCloseHandel(done) {
      this.$refs.form.clearValidate()
      done()
    },
    /* 打开平面图窗口 */
    handlePlan(row) {
      this.uploadData.showFileList = []
      this.uploadData.extData = {}

      listFile(row.fid).then((response) => {
        response.data.forEach(id => {
          this.uploadData.showFileList.push(
            { url: process.env.VUE_APP_BASE_API + '/file/download?fileKey=' + id, fid: id }
          )
        })
        this.uploadData.extData.fid = row.fid
        this.uploadData.dialogVisible = true
      }).catch()
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm(
        `是否要删除基础工程：${row.fnameL2} 的数据项?`,
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(function() {
          return delBuildingManage(row.fid)
        })
        .then(() => {
          this.getBaseEngineeList()
          this.msgSuccess('删除成功')
        })
        .catch(function() {
        })
    },
    /* 关闭前清空数据 */
    clearPicture(done) {
      this.uploadData.showFileList = []
      this.uploadData.extData = {}
      done()
    },
    /* 上传图片前 */
    beforeUpload(file) {
      const file_type = file.type
      const isLt2M = file.size / 1024 / 1024 < 2
      const accept_type = ['image/jpeg', 'image/png', 'image/jpg']
      const accept = accept_type.includes(file_type)
      if (!accept) {
        this.msgError('上传图片只能是 JPG/PNG 格式!')
        return false
      }
      if (!isLt2M) {
        this.msgError('上传图片大小不能超过 2MB!')
        return false
      }
      return accept && isLt2M
    },
    /* 上传图片 */
    uploadImage(e) {
      const formData = new FormData()
      formData.append('fid', '')
      formData.append('file', e.file)
      this.uploadData.newFileList.push(formData)
    },
    /* 删除图片 */
    handleRemovePic(file, fileList) {
      if (file.fid) {
        this.$confirm('此操作将永久删除附件, 是否继续?', '删除附件', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delFile(file.fid).then(response => {
            this.$message.success('附件删除成功。')
          }).catch(() => {
            fileList.push(file)
          })
        }).catch(() => {
          fileList.push(file)
        })
      }
    },
    /* 预览 */
    handlePictureCardPreview(file) {
      this.uploadData.previewUrl = file.url
      this.uploadData.openPreview = true
    },
    // 打开新增防火分区弹窗
    openFireCompart(row) {
      const { cfcurprojectid, fid } = row
      this.$refs.EditFireCompart.open({ cfcurprojectid, parentId: fid, publicareatype: 5 })
    }
  }
}
</script>
<style type="scss" scoped>
.top-panel{
  height: 40px;
}
.add-btn {
  margin-left: 10px;
  display: inline-block;
}
</style>
